using NUnit.Framework;
using ValidationFramework;
using ValidationFramework.Reflection;

namespace ExampleLibraryCSharp
{
    public class TypeCacheExample
    {
        #region Example
        public class Car
        {

            //Assume for the purposes of this sample that cars can have between 2 and 5 doors.
            public int NumberOfDoors
            {
                get;
                set;
            }
        }

        [TestFixture]
        public class ExampleUsage
        {
            [Test]
            public void Run()
            {
                

                var carType = typeof(Car);

                var rangeRule = new RangeRule<int>(null, false, 2, 5, true, true);

                var typeDescriptor = TypeCache.GetType(carType.TypeHandle);
                //create a PropertyDescriptor for NumberOfDoors and add a RangeRule to it.  
                var propertyDescriptor = typeDescriptor.GetOrCreatePropertyDescriptor("NumberOfDoors");
                propertyDescriptor.Rules.Add(rangeRule, null);

                var car = new Car();

                //Create a PropertyValidationManager for Car
                var manager = ValidationManagerFactory.GetPropertyValidationManager(car);
                // 0 is an invalid NumberOfDoors 
                manager.ValidateAll();
                Assert.IsFalse(manager.IsValid);

                // 1 is an invalid NumberOfDoors 
                car.NumberOfDoors = 1;
                manager.ValidateAll();
                Assert.IsFalse(manager.IsValid);

                // 2 is an invalid NumberOfDoors 
                car.NumberOfDoors = 2;
                manager.ValidateAll();
                Assert.IsTrue(manager.IsValid);


                // 6 is an invalid NumberOfDoors 
                car.NumberOfDoors = 6;
                manager.ValidateAll();
                Assert.IsFalse(manager.IsValid);

                // clear the rule
                propertyDescriptor.Rules.Clear();


                // 6 is now a valid NumberOfDoors because the validation rule has been 
                // removed.
                manager.ValidateAll();
                Assert.IsTrue(manager.IsValid);
            }
        }
        #endregion
    }
}